<?php
  header('Expires: 0');
  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  header('Pragma: public');
?>
<html>
<body>
<?php

include_once "conf.php";
include_once "Properties.cls.php";


$props = new Properties();
$props->load(fopen(CONF_LOCATION, "r"));

$restoreFilesPath = $props->getProperty("restoreFilesPath", './restorefiles');

echo "<p><b>Database host:</b> ".$props->getProperty("dbHost", 'localhost')."</p>";
echo "<p><b>Database name:</b> ".$props->getProperty("databaseName", 'helios_test')."</p>";
echo "<p><b>Restore file location: </b>$restoreFilesPath</p>";

if ($_GET["action"] == null || $_GET["action"] == "list") {

  if ($handle = opendir($restoreFilesPath)) {

    echo "<table border='2'><tr><th>File</th><th>Size</th><th>Date</th><th>Restore</th><th>Download</th></tr>";
    /* This is the correct way to loop over the directory. */
    while (false !== ($file = readdir($handle))) {
        if(strpos($file, ".") != 0) {
          echo "<tr><td>$file</td><td>".formatBytes(filesize($restoreFilesPath."/".$file))."</td><td>".date("F d Y H:i:s.", filemtime($restoreFilesPath."/".$file))."</td><td><a href='restore.php?action=restore&name=".urlencode($file)."'>Restore</a></td><td><a href='download.php?name=".urlencode($file)."'>Download</a></td></tr>";
        }
    }
    closedir($handle);
  }
  echo "</table>";
} else if($_GET["action"] == "restore") {

  $dbPassword = $props->getProperty('dbPassword', '');
  
  $command = "mysql -u ".$props->getProperty('dbUser', 'root').(empty($dbPassword) ?'':' -p').$props->getProperty('dbPassword', '')." -h ".$props->getProperty('dbHost', 'localhost')." ".$props->getProperty('databaseName', 'helios_test')." < " .$restoreFilesPath."/".$_GET['name'];
  print $command;
  print $_GET['name'];
  echo exec($command, $output, $result);

    foreach ($output as $outputRow) {
        echo $outputRow."<br/>";
    }

  if($result != 0) {

    echo "<br/>Failed";
  } else {
     echo "<br/>Success";
  }

} else if($_GET["action"] == "download") {

}


function formatBytes($bytes, $precision = 2) {
    $units = array('B', 'KB', 'MB', 'GB', 'TB');

    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);

    $bytes /= pow(1024, $pow); 

    return round($bytes, $precision) . ' ' . $units[$pow];
}

?>
</body>
</html>
